<?php

header("Content-type: text/json; charset=utf-8");
header('Access-Control-Allow-Origin:*');

include_once './utils/Cookie.php';
include_once './db/alarmDB.php';
include_once './db/SignFieldDB.php';
include_once './utils/Tools.php';

function dd($data = "", $isDie = true)
{
    header("content-type:text/html;charset=utf-8");
    echo "<pre>";
    if ($data === true) {
        print_r("true");
    } elseif ($data === false) {
        print_r("false");
    } else {
        print_r($data);
    }
    echo "</pre>";
    if ($isDie) die;
}

class Main{
    protected $whiteRulesArr;
    public function __construct() {
        $this->whiteRulesArr = (new Tools())->getAllFileNameInDir(dirname(__FILE__)."\\rules");
    }

    /**
     * 实例字段类型
     * @param $one
     * @return RuleInterface|Rule
     */
    public function instanceRule($one)
    {
        return self::ruleFactory($one['ruleId']);
    }


    /**
     * 字段对象工厂
     * @param $type
     * @return RuleInterface|Rule
     */
  
    public function ruleFactory($type)
    {
        $class_name = $type."Rule";
        $factory_name = $class_name.".php";
        // 添加反注入代码 （白名单）
        $isin = in_array($factory_name,$this->whiteRulesArr);
        if(!$isin) return false;
        $path_name = __DIR__. "\\rules\\" . $factory_name; //容易被注入
        if(!file_exists($path_name)) return false;
        require_once($path_name);
        return new $class_name();
    }

    /**
     * 检查结果
     * @param $one
     * @return bool
     */
    public function checkRule($one)
    {
        $data = array(
            'result' => 1,
            'msg' => '失败',
            'data' => null
            );
        try{
            $ruleInstance = self::instanceRule($one);
            return $ruleInstance->check($one);
        }catch(\Exception $e){
            $data['msg'] = $e->getMessage();
            echo(json_encode($data, JSON_UNESCAPED_UNICODE));
            return;
        }
    }

    public function router($arr){
        if(!is_array($arr)) return false;
        $array = [];
        foreach ($arr as $key => $value) {
            // var_dump($key);
            // echo "<br/>";
            // var_dump($value);
            // echo "<br/>";
            $res = self::checkRule($value);
            // $value['result'] = $res;
            // array_push($array,$value);
            array_push($array,$res);
            // if($res) self::doAlarm($value);
        }
        dd($array);
        return $array;
    }

    // public function doAlarm($one){ }
}



function doMain()
{
    // 测试修改报警状态
    // $arr=array(1,2,3);
    // $res = (new Alarm())->upDateIsAlarm($arr);  

    // 测试修改最后一次操作id值
    // $res = (new SignField())->update("lastIndex", 30);  //改

    $list = (new Alarm())->getList();             //更新条目（已排序，最新的在前）
    $res = (new Main())->router($list);           //依次进入所属规则内判断
}


if (!empty( $_GET['q'])){
    $q = $_GET['q'];
    (new Alarm())->$q();    //?cmd=api_addRecord
}
else{
    doMain();
}



